package com.hspedu.seckill.controller;

import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.service.GoodsService;
import com.hspedu.seckill.vo.GoodsVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    //装配GoodsService
    @Resource
    private GoodsService goodsService;

    //装配RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;

    //装配手动渲染需要的模板解析器
    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;

    //跳转到商品列表页-到DB查询
    // @RequestMapping("/toList")
    // //public String toList(HttpSession session,
    // //                     Model model,
    // //                     @CookieValue("userTicket")String ticket){
    // //public String toList(Model model,
    // //                     @CookieValue("userTicket")String ticket,
    // //                     HttpServletRequest request,
    // //                     HttpServletResponse response){
    // public String toList(Model model,
    //                      User user){
    //     //如果 cookie 没有生成
    //     //if (!StringUtils.hasText(ticket)){
    //     //    return "login";
    //     //}
    //
    //     //User user = (User)session.getAttribute(ticket);
    //
    //     //从Redis来获取用户
    //     //User user = userService.getUserByCookie(ticket, request, response);
    //
    //     //如果用户没有登录
    //     if (null == user){
    //         return "login";
    //     }
    //
    //     //将user信息放入model给前端模板使用
    //     model.addAttribute("user",user);
    //
    //     //将商品列表信息放入到Model，给下一个模板使用
    //     model.addAttribute("goodsList", goodsService.findGoodsVo());
    //     return "goodsList";
    // }


    //跳转到商品列表页-到Redis查询
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,
                         User user,
                         HttpServletRequest request,
                         HttpServletResponse response) {

        //如果用户没有登录
        if (null == user) {
            WebContext webContext = new WebContext(request, response, request.getServletContext(), response.getLocale());
            String login = thymeleafViewResolver.getTemplateEngine().process("login", webContext);
            return login;
        }

        //先到redis获取页面，如果有，就直接返回
        String html = (String) redisTemplate.opsForValue().get("goodsList");


        if (StringUtils.hasText(html)) {
            return html;
        }

        //将user信息放入model给前端模板使用
        model.addAttribute("user", user);

        //将商品列表信息放入到Model，给下一个模板使用
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        //如果从redis没有获取到页面，就手动渲染，并存入到redis
        WebContext webContext = new WebContext(request, response, request.getServletContext(), response.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);

        if (StringUtils.hasText(html)) {
            //将页面保存到redis，设置每60s更新一次
            redisTemplate.opsForValue().set("goodsList", html, 60, TimeUnit.SECONDS);
        }

        return html;
    }

    //进入到商品详情页面-到DB查询
    // @RequestMapping("/toDetail/{goodsId}")
    // public String toDetail(@PathVariable Long goodsId, User user, Model model) {
    //     if (null == user) {
    //         return "login";
    //     }
    //
    //     //将user传入到model
    //     model.addAttribute("user", user);
    //     //通过goodsId,获取指定的秒杀商品信息
    //     GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
    //     //将查询到的goodsVo放入到model，给下一个模板使用
    //     model.addAttribute("goods", goodsVo);
    //
    //     //返回秒杀商品详情时，同时返回该商品的秒杀的剩余时间
    //     //为了配合前端展示秒杀商品的状态
    //     //1. 定义变量: secKillStatus 秒杀状态 0:秒杀未开始 1:秒杀进行中 2: 秒杀已结束
    //     //2. 定义变量: remainSeconds 剩余秒数: >0: 表示还有多久开始秒杀 0: 秒杀进行中 -1:秒杀已结束
    //
    //     //秒杀开始时间
    //     Date startDate = goodsVo.getStartDate();
    //     //秒杀结束时间
    //     Date endDate = goodsVo.getEndDate();
    //     //当前时间
    //     Date nowDate = new Date();
    //
    //     //秒杀状态
    //     int secKillStatus = 0;
    //     //剩余秒数
    //     int remainSeconds = 0;
    //
    //     if (nowDate.before(startDate)) {//秒杀未开始
    //         remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
    //     } else if (nowDate.after(endDate)) {//秒杀已结束
    //         secKillStatus = 2;
    //         remainSeconds = -1;
    //     } else {//秒杀进行中
    //         secKillStatus = 1;
    //     }
    //
    //     //将secKillStatus 和 remainSeconds 放入model，携带给模板页使用
    //     model.addAttribute("secKillStatus", secKillStatus);
    //     model.addAttribute("remainSeconds", remainSeconds);
    //     return "goodsDetail";
    // }

    //进入到商品详情页面-到redis查询
    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(@PathVariable Long goodsId,
                           User user,
                           Model model,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        if (null == user) {
            WebContext webContext = new WebContext(request, response, request.getServletContext(), response.getLocale());
            String login = thymeleafViewResolver.getTemplateEngine().process("login", webContext);
            return login;
        }

        //先到redis获取页面，如果有，就直接返回
        String html = (String) redisTemplate.opsForValue().get("goodsDetail:" + goodsId);

        if (StringUtils.hasText(html)) {
            return html;
        }


        //将user传入到model
        model.addAttribute("user", user);
        //通过goodsId,获取指定的秒杀商品信息
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        //将查询到的goodsVo放入到model，给下一个模板使用
        model.addAttribute("goods", goodsVo);

        //返回秒杀商品详情时，同时返回该商品的秒杀的剩余时间
        //为了配合前端展示秒杀商品的状态
        //1. 定义变量: secKillStatus 秒杀状态 0:秒杀未开始 1:秒杀进行中 2: 秒杀已结束
        //2. 定义变量: remainSeconds 剩余秒数: >0: 表示还有多久开始秒杀 0: 秒杀进行中 -1:秒杀已结束

        //秒杀开始时间
        Date startDate = goodsVo.getStartDate();
        //秒杀结束时间
        Date endDate = goodsVo.getEndDate();
        //当前时间
        Date nowDate = new Date();

        //秒杀状态
        int secKillStatus = 0;
        //剩余秒数
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {//秒杀未开始
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {//秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {//秒杀进行中
            secKillStatus = 1;
        }

        //将secKillStatus 和 remainSeconds 放入model，携带给模板页使用
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        //如果从redis没有获取到页面，就手动渲染，并存入到redis
        WebContext webContext = new WebContext(request, response, request.getServletContext(), response.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);

        //将页面保存到redis，设置每60s更新一次
        if (StringUtils.hasText(html)) {
            redisTemplate.opsForValue().set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }

        return html;
    }
}
